package org.vaadin.golfscoretracker.ui.components;

import org.vaadin.appfoundation.i18n.Lang;
import org.vaadin.appfoundation.i18n.TranslationUtil;
import org.vaadin.golfscoretracker.data.Course;
import org.vaadin.golfscoretracker.data.RoundSet;
import org.vaadin.golfscoretracker.ui.controller.CourseController;

import com.vaadin.data.Item;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.PopupDateField;
import com.vaadin.ui.Select;

public class RoundSetFieldFactory extends DefaultFieldFactory {

    private static final long serialVersionUID = 6306949463806908301L;

    private final CourseEditor editor = new CourseEditor();

    @Override
    public Field createField(Item item, Object propertyId, Component uiContext) {
        Field field = null;
        if (propertyId.equals("date")) {
            field = new PopupDateField();
            ((PopupDateField) field)
                    .setResolution(PopupDateField.RESOLUTION_DAY);
        } else if (propertyId.equals("course")) {
            field = new Select();
            ((Select) field).setContainerDataSource(new CourseController()
                    .getContainer());
            ((Select) field).setItemCaptionPropertyId("name");
            ((Select) field).setImmediate(true);
            ((Select) field).addListener(new ValueChangeListener() {
                private static final long serialVersionUID = 8295454209038366843L;

                @Override
                public void valueChange(ValueChangeEvent event) {
                    Course course = (Course) event.getProperty().getValue();
                    editor.setCourse(course);
                }
            });
        } else if (propertyId.equals("rounds")) {
            field = editor;
        }

        if (field != null) {
            field.setCaption(TranslationUtil.getFieldTranslation(
                    RoundSet.class, (String) propertyId));
            field.setRequired(true);
            field.setRequiredError(Lang.getMessage("required validator"));
        }

        return field;
    }

}
